package com.lingnan.config;

/**
 * @Author 梁兴达
 * @Date 2022/3/21 21:14:43
 * @Version 1.0
 */

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;


/**
 * 上传文件
 */
@Component
@ConfigurationProperties(prefix = "oss.qiniu")//通过spring boot中ConfigurationProperties注解的配置yml赋值
@Data
public class QiNiuCouldConfig {
    //域名
    private String path;
    //工钥
    private String accessKey;
    //密钥
    private String secretKey;
    //空间名
    private String bucket;

    /**
     * 上传云存储
     * @param inputStream
     * @param fileName
     * @return
     * @throws QiniuException
     */
    public String uploadImageQiNiu(InputStream inputStream , String fileName) throws QiniuException {
        //构造一个指定区域对象配置类
        Configuration configuration = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(configuration);
        //构造凭证对象
        Auth auth = Auth.create(accessKey, secretKey);
        //将空间名加进去
        String uploadToken = auth.uploadToken(bucket);

        //字节流做法
//        String fileUrl = path+File.separator+fileName;
//        File file = new File(fileName);
//        Response responseFile = uploadManager.put(fileUrl,fileName,uploadToken);
//
        Response response = uploadManager.put(inputStream,fileName,uploadToken,null,null);
        DefaultPutRet defaultPutRet =new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //外网地址可以通过地址访问上传的图片
        String returnImageUrl = path+ File.separator+defaultPutRet.key;
        System.out.println(returnImageUrl);
//        Map<String, String> map = new HashMap<>();
//        map.put("imageName",defaultPutRet.key);
//        map.put("returnImageUrl",returnImageUrl);
        return returnImageUrl;
    }

    /**
     * 删除云存储
     * @param fileName
     * @throws QiniuException
     */
    public void deleteImageQiNiu(String fileName) throws QiniuException {
        //构造一个指定区域对象配置类
        Configuration configuration = new Configuration(Region.region2());
        //构造凭证对象
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, configuration);
        bucketManager.delete(bucket, fileName);
    }

}